#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

class Person
{
public:
	string name;
	int age;
};

int main(int argc, char const *argv[])
{
	// 写入数据到文件
	ofstream outFile("test.txt");
	if (!outFile.is_open())
	{
		cout << "打开文件失败以写入" << endl;
		return 1;
	}

	Person person1 = {"Alice", 30};
	Person person2 = {"Bob", 25};
	// 将结构体数据以文本形式写入文件，使用逗号作为分隔符
	outFile << person1.name << "," << person1.age << endl;
	outFile << person2.name << "," << person2.age << endl;
	outFile.close();

	// 读取文件内容
	ifstream inFile("test.txt");
	if (!inFile.is_open())
	{
		cout << "打开文件失败以读取" << endl;
		return 1;
	}

	Person person;
	cout << "读取文件内容:" << endl;
	string line;
	while (getline(inFile, line))
	{
		stringstream ss(line);
		// 从字符串流中解析数据
		getline(ss, person.name, ',');
		ss >> person.age;
		cout << "姓名: " << person.name << " 年龄: " << person.age << endl;
	}
	inFile.close();

	return 0;
}